# -*-coding: utf-8 -*-
"""
    @Theme   : View Functions
    @Time    : 2024/6/18 16:12
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import re
import time
import hashlib
from datetime import datetime
from functools import wraps

from urllib.parse import quote, unquote
from flask import render_template, request, redirect, jsonify, current_app


from chatroom import app, r_client


def login_required(func):
    @wraps(func)
    def wrapper(**view_args):
        nick = unquote(request.cookies.get('name', ''))
        s_token = r_client.get_token(nick)
        if (not s_token) or s_token != request.cookies.get('token', ''):
            return redirect('/')
        return func(**view_args)

    return wrapper


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['POST'])
def login():
    nick = request.json.get('nick', '').strip()

    if not nick:
        return jsonify({'success': False, 'reason': '昵称不能为空！'})

    if not re.match(r'^[\w\s]{1,30}$', nick):
        return jsonify({'success': False, 'reason': '昵称不合法！'})

    if r_client.is_nick_already_exists(nick):
        return jsonify({'success': False, 'reason': f'昵称 {nick} 已被占用！'})

    token = hashlib.md5(f'{nick}{time.time()}'.encode()).hexdigest()

    r_client.set_token(nick, token)

    res = jsonify({'success': True, 'token': token})
    res.set_cookie('name', quote(nick, safe=''), max_age=current_app.config['CHAT_COOKIE_EXPIRE_TIME'])
    res.set_cookie('token', token, max_age=current_app.config['CHAT_COOKIE_EXPIRE_TIME'])

    return res


@app.route('/room')
@login_required
def room():
    return render_template('chat_room.html')


@app.route('/get_chat_list')
@login_required
def get_chat_list():
    chat_list = r_client.get_chat_list()
    return jsonify(chat_list)


@app.route('/post_message', methods=['POST'])
@login_required
def post_message():
    message = request.json
    msg = message.get('msg', '')
    nick = message.get('nick', '')

    if not all([msg, nick]):
        return jsonify({'success': False, 'reason': '昵称或聊天内容为空！'})

    expire_time = r_client.get_msg_expire_time(nick, msg)

    if expire_time == -2:
        # msg not exists
        message_info = {
            'msg': message['msg'],
            'post_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'nick': message['nick']
        }
        r_client.push_chat_info(message_info)
        r_client.set_msg_expire_time(nick, msg)
        return jsonify({'success': True})
    elif expire_time > 0:
        return jsonify({'success': False,
                        'reason': f'两分钟内禁止发送同样的内容！还剩 {expire_time} 秒'})
